import { getArticleList, getArticleListRefresh } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'

import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleItem from '../ArticleItem'

import styles from './index.module.scss'

type Props = {
  channelId: number
}

const ArticleList = ({ channelId }: Props) => {
  const dispatch = useDispatch()
  const history = useHistory()

  // useEffect(() => {
  //   dispatch(getArticleList(channelId, +new Date() + ''))
  // }, [dispatch, channelId])

  //从redux中 取出整个tab栏所有的数据
  const { channelArticles } = useSelector((state: RootState) => state.home)
  //根据id,取出对应的栏目数据
  const { timestamp, articles = [] } = channelArticles[channelId] || {}

  //一旦没数据了，timestamp 的值，后台会返回 null
  const hasMore = timestamp === null ? false : true

  //loadMore 一开始数据为空，自动发送一次请求
  //1.进入页面执行一次
  //2.触底了，还会发一次
  const loadMore = async () => {
    console.log('需要加载更多数据')
    await dispatch(getArticleList(channelId, timestamp || +new Date() + ''))
  }
  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <PullToRefresh
        onRefresh={async () => {
          //重新发送请求，获取最新的数据，传当前的时间戳
          await dispatch(getArticleListRefresh(channelId, +new Date() + ''))
        }}
      >
        {articles.map((item) => (
          <div
            onClick={() => history.push(`/article/${item.art_id}`)}
            key={item.art_id}
            className="article-item"
          >
            <ArticleItem article={item} />
          </div>
        ))}
        {/* 无限加载组件 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
